﻿using RpcCacheClient.Interface;
using RpcCentral.Collect.Model;
using RpcCentral.DAL;
using RpcCentral.Model.DB;
using RpcHelper;
using RpcModel;
using SqlSugarHelper;

namespace RpcCentral.Collect.Collect
{
    /// <summary>
    /// 容器管理
    /// </summary>
    internal class ContainerCollect : IContainerCollect
    {
        private readonly IRemoteServerDAL _RemoteServer;
        private readonly IContainerDAL _Container;
        private readonly ICacheController _Cache;
        private readonly ITransactionService _Transaction;
        public ContainerCollect(IRemoteServerDAL remoteServer,
            ICacheController cache,
            ITransactionService transaction,
            IContainerDAL container)
        {
            _Transaction = transaction;
            _Cache = cache;
            _RemoteServer = remoteServer;
            _Container = container;
        }

        public Guid RegContainer(ContrainerLogin param)
        {
            string key = string.Concat("Con_", param.ContrainerId, "_", (int)param.ContainerType);
            if (_Cache.TryGet(key, out Guid id))
            {
                return id;
            }
            id = _Container.Find(param.ContainerType, param.ContrainerId);
            if (id == Guid.Empty)
            {
                id = _AddContrainer(param);
            }
            _Cache.Set(key, id);
            return id;
        }
        private Guid _AddContrainer(ContrainerLogin param)
        {
            if (param.LocalMac == null)
            {
                param.LocalMac = Tools.GetRandomMac();
            }
            Contrainer add = new Contrainer
            {
                ContrainerId = param.ContrainerId,
                VirtualMac = param.LocalMac,
                ContainerType = param.ContainerType
            };
            RemoteServerConfig server = new RemoteServerConfig
            {
                SystemType = param.SystemType,
                ServerIp = param.ServerIp,
                ServiceState = RpcServiceState.待启用,
                IsContainer = true,
                GroupId = param.GroupId,
                PublicKey = Tools.GetRandomStr(12),
                ServerPort = param.ServerPort,
                ServerMac = add.VirtualMac,
                IsEnablePipe = false,
                ConIp = param.ServerIp,
                ServerName = string.Concat(param.ContainerType.ToString(), "容器_", param.SystemName, "节点"),
                RemoteIp = param.ServerIp
            };
            using (ILocalTransaction tran = _Transaction.ApplyTran())
            {
                server.ContainerId = _Container.Reg(add);
                _RemoteServer.Add(server);
                tran.Commit();
            }
            return server.ContainerId.Value;
        }
    }
}
